package com.hj.exception;

import com.hj.domain.LoginUser;
import com.hj.response.Resp;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @Description 全局异常处理器
 * @author hj
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(ParamsException.class)
    public Resp<ParamsException> handlerOrgUserException(ParamsException e) {
        e.printStackTrace();
        return new Resp<>(e.getCode(), e.getMsg());
    }


    @ExceptionHandler(AccessDeniedException.class)
    public Resp<String> handleAccessDeniedException(AccessDeniedException e) {
        Resp<Object> exceptionResp = new Resp<>();
        exceptionResp.setMsg("无权限访问该接口");
        exceptionResp.setData(null);
        exceptionResp.setStatus(403);
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        if (null == loginUser || loginUser.getId() == null) {
            return new Resp<>("没有登录");
        }
        return new Resp<>("无权限访问该接口");
    }


}
